<?
  require_once('../db.php');
  require_once('../util/misc.php');
  require_once('../util/pointinpolygon.php');
  require_once('boundaries.php');
  db_connect();

  $query = 'select id_TPT as id, latitude_TPT as lat, longitude_TPT as lng, AsText(location_TPT) as pt, codeCNT_TPT as cnt from ldi_trash_point_tpt';
  $result = mysql_query($query) or die("ERROR PERFORMING QUERY '".$query."': ".mysql_error());

  function find_county($lat, $lng) {
    $p = array($lng, $lat);
    $num = count($GLOBALS["codes"]);
    for ($i=0; $i<$num; $i++)
      if (pointInPolygon($p, $GLOBALS["boundaries"][$GLOBALS["judete"][$i]]))
        return $GLOBALS["codes"][$i];
    return "ERR";
  }

  while ($row = mysql_fetch_assoc($result)) {
    if (is_null($row["pt"]) && !is_null($row["lat"]) && !is_null($row["lng"])) {
      $q = "update ldi_trash_point_tpt set location_TPT=GeomFromText('POINT(".$row["lng"]." ".$row["lat"].")') WHERE id_TPT=".$row["id"];
      echo $q."\n";
      mysql_query($q) or die("ERROR PERFORMING QUERY '".$q."': ".mysql_error());
    }

    if (is_null($row["cnt"]) || $row["cnt"] === "" /* || $row["id"] > 83078 */) {
      // $oldcounty = $row["cnt"];
      $county = find_county($row["lat"], $row["lng"]);
      // if ($oldcounty != $county)
      //   echo $row["id"]." ".$oldcounty." ".$county."\n";
      if ($county !== "ERR") {
        $q = "update ldi_trash_point_tpt set codeCNT_TPT='".$county."' WHERE id_TPT=".$row["id"];
        echo $q."\n";
        mysql_query($q) or die("ERROR PERFORMING QUERY '".$q."': ".mysql_error());
      }
      else
        echo "ERR: ".$row["id"]." OUTSIDE ROMANIA\n";
    }

    fflush(stdout);
  }

  mysql_free_result($result);

?>
